package com.rrd.hive.udf;

import com.rrd.hive.util.PIDValidator;
import com.weicai.caesar.CaesarUtil;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

@Description(
        name = "pid_gender",
        value = "_FUNC_(pid) - Get gender from pid or caesar encode pid",
        extended = "Example:\n> SELECT _FUNC_('110106201012310313');\n  1\n> SELECT _FUNC_('110106201012310323');\n  2\n  1:男 2:女"
)
public class PidGenderUDF extends UDF {
    public Text evaluate(String pid) {
        if (pid == null || pid.equals("")) {
            return null;
        }
        if (CaesarUtil.isEncrypted(pid)) {
            pid = CaesarUtil.decode(pid);
        }
        if (!PIDValidator.isValidIDCard(pid)) {
            return null;
        }
        Text text = new Text();
        String usex = "";
        if (pid != null) {
            if (pid.length() == 18) {
                usex = pid.substring(16, 17);// 用户的性别
            } else if (pid.length() == 15) {
                usex = pid.substring(14, 15);// 用户的性别
            }
            try {
                if (Integer.parseInt(usex) % 2 == 0) {
                    text.set("2");  //女
                } else {
                    text.set("1");  //男
                }
            } catch (NumberFormatException ignored) {
            }
        }
        return text;
    }

    public static void main(String[] args) {
        PidGenderUDF dfu = new PidGenderUDF();
        System.out.println(dfu.evaluate(CaesarUtil.encode("110106198705170313")));
    }

}
